<template>
  <div class="repository-branches-container">
    <div class="page-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <div class="page-info">
          <h1>分支管理</h1>
          <p>{{ repository.name }}</p>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" icon="Plus" @click="showCreateDialog = true">
          新建分支
        </el-button>
      </div>
    </div>

    <div class="branches-content">
      <el-card>
        <div class="branches-list">
          <div 
            v-for="branch in branches"
            :key="branch.name"
            class="branch-item"
            :class="{ 'default-branch': branch.isDefault }"
          >
            <div class="branch-info">
              <div class="branch-header">
                <div class="branch-name">
                  <el-icon><Branch /></el-icon>
                  <span>{{ branch.name }}</span>
                  <el-tag v-if="branch.isDefault" type="success" size="small">默认分支</el-tag>
                  <el-tag v-if="branch.isProtected" type="warning" size="small">受保护</el-tag>
                </div>
                <div class="branch-actions">
                  <el-button size="small" @click="viewBranch(branch)">查看</el-button>
                  <el-button size="small" @click="compareBranch(branch)">对比</el-button>
                  <el-dropdown @command="handleBranchAction">
                    <el-button size="small">
                      更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{action: 'merge', branch}">合并</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'protect', branch}" v-if="!branch.isProtected">保护</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'unprotect', branch}" v-if="branch.isProtected">取消保护</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'delete', branch}" v-if="!branch.isDefault" divided>删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
              
              <div class="branch-details">
                <div class="branch-stats">
                  <span class="stat-item">
                    <el-icon><Commit /></el-icon>
                    {{ branch.commitCount || 0 }} 个提交
                  </span>
                  <span class="stat-item">
                    <el-icon><Clock /></el-icon>
                    最后更新：{{ formatTime(branch.lastUpdate) }}
                  </span>
                  <span class="stat-item" v-if="branch.ahead || branch.behind">
                    <el-icon><Compare /></el-icon>
                    <span v-if="branch.ahead" class="ahead">领先 {{ branch.ahead }}</span>
                    <span v-if="branch.behind" class="behind">落后 {{ branch.behind }}</span>
                  </span>
                </div>
                
                <div class="last-commit" v-if="branch.lastCommit">
                  <div class="commit-message">{{ branch.lastCommit.message }}</div>
                  <div class="commit-meta">
                    <span class="commit-author">{{ branch.lastCommit.author }}</span>
                    <span class="commit-hash">{{ branch.lastCommit.hash.substring(0, 8) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 创建分支对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建新分支"
      width="500px"
    >
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="100px">
        <el-form-item label="分支名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入分支名称" />
        </el-form-item>
        <el-form-item label="基于分支" prop="baseBranch">
          <el-select v-model="createForm.baseBranch" placeholder="选择基于分支" style="width: 100%">
            <el-option 
              v-for="branch in branches"
              :key="branch.name"
              :label="branch.name"
              :value="branch.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分支描述" prop="description">
          <el-input
            v-model="createForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分支描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createBranch" :loading="creating">创建</el-button>
      </template>
    </el-dialog>

    <!-- 合并分支对话框 -->
    <el-dialog
      v-model="showMergeDialog"
      title="合并分支"
      width="500px"
    >
      <el-form :model="mergeForm" label-width="100px">
        <el-form-item label="源分支">
          <el-input v-model="mergeForm.sourceBranch" disabled />
        </el-form-item>
        <el-form-item label="目标分支">
          <el-select v-model="mergeForm.targetBranch" placeholder="选择目标分支" style="width: 100%">
            <el-option 
              v-for="branch in branches.filter(b => b.name !== mergeForm.sourceBranch)"
              :key="branch.name"
              :label="branch.name"
              :value="branch.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合并类型">
          <el-radio-group v-model="mergeForm.mergeType">
            <el-radio label="merge">普通合并</el-radio>
            <el-radio label="squash">压缩合并</el-radio>
            <el-radio label="rebase">变基合并</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="合并说明">
          <el-input
            v-model="mergeForm.message"
            type="textarea"
            :rows="3"
            placeholder="请输入合并说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showMergeDialog = false">取消</el-button>
        <el-button type="primary" @click="mergeBranch" :loading="merging">合并</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getRepositoryDetail,
  getRepositoryBranches,
  createBranch as apiCreateBranch,
  deleteBranch as apiDeleteBranch,
  mergeBranch as apiMergeBranch,
  protectBranch,
  unprotectBranch
} from '@/api/version'
import { formatTime } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const repository = ref({})
const branches = ref([])
const showCreateDialog = ref(false)
const showMergeDialog = ref(false)
const creating = ref(false)
const merging = ref(false)
const createFormRef = ref()

// 表单数据
const createForm = reactive({
  name: '',
  baseBranch: '',
  description: ''
})

const mergeForm = reactive({
  sourceBranch: '',
  targetBranch: '',
  mergeType: 'merge',
  message: ''
})

// 表单验证规则
const createRules = {
  name: [
    { required: true, message: '请输入分支名称', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '分支名称只能包含字母、数字、下划线和连字符', trigger: 'blur' }
  ],
  baseBranch: [
    { required: true, message: '请选择基于分支', trigger: 'change' }
  ]
}

// 页面加载
onMounted(async () => {
  await loadRepository()
  await loadBranches()
})

// 加载仓库信息
const loadRepository = async () => {
  try {
    const response = await getRepositoryDetail(route.params.id)
    if (response.code === 200) {
      repository.value = response.data
    }
  } catch (error) {
    console.error('获取仓库信息失败:', error)
    ElMessage.error('获取仓库信息失败')
  }
}

// 加载分支列表
const loadBranches = async () => {
  try {
    const response = await getRepositoryBranches(route.params.id)
    if (response.code === 200) {
      branches.value = response.data || []
      if (branches.value.length > 0 && !createForm.baseBranch) {
        createForm.baseBranch = branches.value.find(b => b.isDefault)?.name || branches.value[0].name
      }
    }
  } catch (error) {
    console.error('获取分支列表失败:', error)
    ElMessage.error('获取分支列表失败')
  }
}

// 查看分支
const viewBranch = (branch) => {
  router.push(`/version/repository/${route.params.id}?branch=${branch.name}`)
}

// 对比分支
const compareBranch = (branch) => {
  router.push(`/version/repository/${route.params.id}/compare/${branch.name}`)
}

// 处理分支操作
const handleBranchAction = async ({ action, branch }) => {
  switch (action) {
    case 'merge':
      mergeForm.sourceBranch = branch.name
      mergeForm.targetBranch = ''
      mergeForm.message = `Merge branch '${branch.name}'`
      showMergeDialog.value = true
      break
    case 'protect':
      await protectBranchAction(branch)
      break
    case 'unprotect':
      await unprotectBranchAction(branch)
      break
    case 'delete':
      await deleteBranchAction(branch)
      break
  }
}

// 创建分支
const createBranch = async () => {
  try {
    await createFormRef.value.validate()
    creating.value = true
    
    await apiCreateBranch({
      repositoryId: route.params.id,
      ...createForm
    })
    
    ElMessage.success('分支创建成功')
    showCreateDialog.value = false
    createForm.name = ''
    createForm.description = ''
    loadBranches()
  } catch (error) {
    console.error('创建分支失败:', error)
    ElMessage.error('创建分支失败')
  } finally {
    creating.value = false
  }
}

// 合并分支
const mergeBranch = async () => {
  if (!mergeForm.targetBranch) {
    ElMessage.warning('请选择目标分支')
    return
  }
  
  try {
    merging.value = true
    await apiMergeBranch({
      repositoryId: route.params.id,
      ...mergeForm
    })
    
    ElMessage.success('分支合并成功')
    showMergeDialog.value = false
    loadBranches()
  } catch (error) {
    console.error('合并分支失败:', error)
    ElMessage.error('合并分支失败')
  } finally {
    merging.value = false
  }
}

// 保护分支
const protectBranchAction = async (branch) => {
  try {
    await protectBranch(route.params.id, branch.name)
    ElMessage.success('分支保护设置成功')
    loadBranches()
  } catch (error) {
    console.error('设置分支保护失败:', error)
    ElMessage.error('设置分支保护失败')
  }
}

// 取消保护分支
const unprotectBranchAction = async (branch) => {
  try {
    await unprotectBranch(route.params.id, branch.name)
    ElMessage.success('已取消分支保护')
    loadBranches()
  } catch (error) {
    console.error('取消分支保护失败:', error)
    ElMessage.error('取消分支保护失败')
  }
}

// 删除分支
const deleteBranchAction = async (branch) => {
  try {
    await ElMessageBox.confirm(`确认要删除分支 ${branch.name} 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await apiDeleteBranch(route.params.id, branch.name)
    ElMessage.success('分支删除成功')
    loadBranches()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分支失败:', error)
      ElMessage.error('删除分支失败')
    }
  }
}

// 返回
const goBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.repository-branches-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .page-info {
      h1 {
        font-size: 24px;
        font-weight: 600;
        margin: 0 0 4px 0;
        color: #303133;
      }
      
      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.branches-content {
  max-width: 1000px;
  margin: 0 auto;
}

.branches-list {
  .branch-item {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.default-branch {
      background-color: #f8f9fa;
    }
    
    .branch-info {
      .branch-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        .branch-name {
          display: flex;
          align-items: center;
          gap: 8px;
          
          span {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
          }
        }
        
        .branch-actions {
          display: flex;
          gap: 8px;
        }
      }
      
      .branch-details {
        .branch-stats {
          display: flex;
          gap: 20px;
          margin-bottom: 12px;
          flex-wrap: wrap;
          
          .stat-item {
            display: flex;
            align-items: center;
            gap: 4px;
            color: #606266;
            font-size: 14px;
            
            .ahead {
              color: #67c23a;
            }
            
            .behind {
              color: #f56c6c;
            }
          }
        }
        
        .last-commit {
          .commit-message {
            color: #303133;
            margin-bottom: 4px;
          }
          
          .commit-meta {
            display: flex;
            gap: 12px;
            font-size: 12px;
            color: #909399;
            
            .commit-hash {
              font-family: monospace;
              background-color: #f5f5f5;
              padding: 2px 4px;
              border-radius: 3px;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .repository-branches-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    padding: 20px;
    
    .header-left {
      width: 100%;
      justify-content: space-between;
    }
  }
  
  .branch-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .branch-stats {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
